<template>
    <a-layout-header class="header">
      <div class="logo">海洋生物知识库</div>

      <a-menu
        theme="dark"
        mode="horizontal"
       :style="{ lineHeight: '64px', display:'block' }"
      >
        <a-menu-item key="/"  :style="{float:'left'}" >
        <router-link to="/">首页</router-link>
      </a-menu-item>
      <a-menu-item key="/admin/user"   :style="{float:'left'}"   >
        <router-link to="/admin/user"  v-show="user.id" >用户管理</router-link>
      </a-menu-item>
      <a-menu-item key="/admin/ebook" :style="{float:'left'}"  >
        <router-link to="/admin/ebook" v-show="user.id" >海洋生物种类管理</router-link>
      </a-menu-item>
      <a-menu-item key="/admin/category" :style="{float:'left'}"  >
        <router-link to="/admin/category"  v-show="user.id" >海洋生物分类管理</router-link>
      </a-menu-item>
      <a-menu-item key="/about"  :style="{float:'left'}" >
        <router-link to="/about">关于我们</router-link>
      </a-menu-item>

      <a-menu-item key="/admin/user"  :style="{float:'right'}"  >
        <span v-show="user?.id" >您好：{{user?.name}}</span>
      </a-menu-item>

      <a-menu-item key="admin/login"  :style="{float:'right'}" >
        <a v-show="!user.id"   @click="showLoginModal">登录</a>
      </a-menu-item> 

      <a-menu-item   :style="{float:'right'}" >
          <a-popconfirm
          title="确认退出登录?"
          ok-text="是"
          cancel-text="否"
          @confirm="logout()"
      >
          <a  v-show="user.id" >退出登录</a>
        </a-popconfirm>
        </a-menu-item>

      </a-menu>


       <a-modal
        title="登录"
        v-model:visible="loginModalVisible"
        :confirm-loading="loginModalLoading"
        @ok="login"
    >
      <a-form :model="loginUser" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="登录名">
          <a-input v-model:value="loginUser.loginName" />
        </a-form-item>
        <a-form-item label="密码">
          <a-input v-model:value="loginUser.password" type="password" />
        </a-form-item>
      </a-form>
    </a-modal>
      
    </a-layout-header>
</template>
<script lang="ts" setup>
import { message,notification } from "ant-design-vue";
import axios from 'axios';
import { defineComponent ,computed ,ref,onMounted } from 'vue';
import {hexMd5,KEY} from '../../public/js/md5.js';
import store from '@/store';
import {Tool} from '../utils/tool'
let websocket:any;
let token:any;
onMounted(() => {
      // 判断当前浏览器是否支持 websocket(H5自带)
      if ('WebSocket' in window) {
        token = Tool.uuid(10);//生成当前客户端token
        // 连接地址：ws://127.0.0.1:8880/ws/xxx
        websocket = new WebSocket(process.env.VUE_APP_WS_SERVER + '/ws/' + token);
        initWebSocket()//初始化

        // 关闭
        // websocket.close();
      } else {
        alert('当前浏览器 不支持')
      }
    });

    const onOpen = () => {
      console.log('WebSocket连接成功，状态码：', websocket.readyState)
    };
    const onMessage = (event: any) => {
      console.log('WebSocket收到消息：', event.data);
      notification['info']({
        message: '收到消息',
        description: event.data,
      });
    };
    const onError = () => {
      console.log('WebSocket连接错误，状态码：', websocket.readyState)
    };
    const onClose = () => {
      console.log('WebSocket连接关闭，状态码：', websocket.readyState)
    };
    const initWebSocket = () => {
      // 连接成功
      websocket.onopen = onOpen;
      // 收到消息的回调
      websocket.onmessage = onMessage;
      // 连接错误
      websocket.onerror = onError;
      // 连接关闭的回调
      websocket.onclose = onClose;
    };

const loginModalVisible = ref(false);
const loginModalLoading = ref(false);
const showLoginModal = () => {
  loginModalVisible.value = true;
};

// const user=ref({});
const user = computed(() => store.state.user);
const loginUser = ref({
  loginName: "",
  password: ""
});

defineComponent({
  name: 'the-header'
});

// 登录
  // const login = () => {
  //     console.log("开始登录");
  //     loginModalLoading.value = true;
  //     loginUser.value.password = hexMd5(loginUser.value.password + KEY);
  //     axios.post('http://localhost:8080/obwiki/user/login', loginUser.value).then((response) => {
  //       loginModalLoading.value = false;
  //       const data = response.data;
  //       if (data.success) {
  //         loginModalVisible.value = false;
  //         console.log("登录成功返回数据:",data);
  //         user.value = data.content;
  //         message.success("登录成功！");
  //       } else {
  //         message.error(data.message);
  //         loginModalLoading.value = false;
  //       }
  //     });
  //   };
  const login = () => {
      console.log("开始登录");
      loginModalLoading.value = true;
      loginUser.value.password = hexMd5(loginUser.value.password + KEY);
      axios.post('http://localhost:8080/obwiki/user/login', loginUser.value).then((response) => {
        loginModalLoading.value = false;
        const data = response.data;
        if (data.success) {
          loginModalVisible.value = false;
          console.log("登录成功返回数据:",data);
          // user.value = data.content;
          // store.commit("setUser",user.value);
           //调用commit方法 参数1 触发方法名 参数2 传入值
           store.commit("setUser",data.content);
          message.success("登录成功！");
        } else {
          message.error(data.message);
          loginModalLoading.value = false;
        }
      });
    };

    // 退出登录
    const logout = () => {
      console.log("退出登录开始");
      axios.get('http://localhost:8080/obwiki/user/logout/' + user.value.token).then((response) => {
        const data = response.data;
        if (data.success) {
          message.success("退出登录成功！");
          store.commit("setUser", {});
        } else {
          message.error(data.message);
        }
      });
    };

</script>
<style>

 .logo {
  float: left;
  width: 150px;
  height: 31px;
  /* margin: 16px 24px 16px 0;
  background: rgba(255, 255, 255, 0.3); */
  color: white;
  font-size: 18px;
}
.login-menu {
  float: right;
  color: white;
  padding-left: 10px;
}
</style>